<template>
  <div>
    <el-form :model="goods" :rules="rules" ref="goodsform" label-position="right" label-width="100px" class="goods-form">
      <div class="goods-title">基本信息</div>
      <!-- 基本信息 -->
      <div>
        <el-form-item v-if='type == 3' label="是否自动发货" class="goods-form-item">
          <el-switch v-model="goods.service_goods_is_ship"  active-color="#13ce66" active-value="1" inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="商品标题" class="goods-form-item" prop="name">
          <el-input v-model="goods.name" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
          <div class="goods-form-item-text">限30个字，60个字符内</div>
        </el-form-item>
        <el-form-item label="短标题" class="goods-form-item" prop="short_name">
          <el-input v-model="goods.short_name" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
          <div class="goods-form-item-text">限12个字</div>
        </el-form-item>
        <el-form-item label="简单说明" class="goods-form-item" prop="simple_info">
          <el-input type="textarea" :rows="1" v-model="goods.simple_info" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
          <div class="goods-form-item-text">在商品详情页标题下面展示卖点信息，200字以内</div>
        </el-form-item>
        <el-form-item label="商品货号" class="goods-form-item">
          <el-input v-model="goods.code" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
        </el-form-item>
        <el-form-item label="商品单位" class="goods-form-item" prop="unit">
          <el-input v-model="goods.unit" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
          <div class="goods-form-item-text">如：件、份、箱</div>
        </el-form-item>
        <el-form-item :label="index === 0 ? '商品属性' : ''" class="goods-form-item" v-for="(item,index) in goods.attribute" :key="index">
          <el-input v-model="goods.attribute[index]" class="goods-form-item-input" placeholder="请输入" size="small"></el-input>
          <el-button type="primary" plain class="goods-form-item-button" v-if="index === 0" @click="goods.attribute.push('')" size="small">添加</el-button>
          <el-button type="danger"  plain class="goods-form-item-button" v-else @click="goods.attribute.splice(index,1)" size="small">删除</el-button>
          <div class="goods-form-item-text" v-if="index === 0">如：品牌、保质期等。在商品详情顶部，以表格的形式显示，最多6条</div>
        </el-form-item>
        <el-form-item label="分类" class="goods-form-item" prop='m_category_id'>
          <div style="width: 50%;">
            <el-select 
              v-model="firstGroupId" 
              placeholder="选择一级分类" 
              style="width: calc(50% - 8px)" 
              size="small" 
              @change="selectGoodsGroup">
              <el-option :label="item.name" :value="item.id" v-for="item in goodGroupList" :key="item.id"></el-option>
            </el-select>
            <el-select 
              v-model="secondGroupId"
              placeholder="选择二级分类" 
              style="width: calc(50% - 8px);margin-left:10px" 
              size="small"
              @change="selectGoodsGroupSecond"
              v-show="firstGroup.length>0">
              <el-option :label="item.name" :value="item.id" v-for="item in firstGroup" :key="item.id"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="销售区域" class="goods-form-item">
          <el-select v-model="goods.city_group_id" placeholder="选择销售区域" class="goods-form-item-input" size="small">
            <el-option label="全国" value=""></el-option>
            <el-option :label="item.name" :value="item.id" v-for="item in goodsAreaList" :key="item.id"></el-option>
          </el-select>
          <div class="goods-form-item-text">选择后代表这个商品只能在这个区域显示销售，不选择则是全国销售</div>
        </el-form-item>
        <el-form-item label="增值服务" class="goods-form-item">
          <div style="width:50%;display:inline-flex">
            <el-input v-model="labels[index]" :style="{flex: 1, 'margin-left': index === 0 ? '0' : '15px'}" placeholder="请输入" size="small" v-for="(item, index) in labels" :key="index"></el-input>
          </div>
          <div class="goods-form-item-text">显示在店铺信息下方，最多4个，每个最多4个字</div>
        </el-form-item>
        <el-form-item label="商品主图" class="goods-form-item" prop="pic_urls">
          <el-button type="primary" plain @click="openMainPicPanel" size="small">选择图片</el-button>
          <div class="goods-form-item-text" style="width:calc(100% - 150px)">建议尺寸：750×750，最多上传5张，支持png、jpg、jpeg格式，大小不超过500KB</div>
        </el-form-item>
        <el-form-item class="goods-form-item" v-if="mainPicList.length>0">
          <l-pic v-for="(item,index) in mainPicList" :key="index"
            :picurl="item"
            :pickey="index"
            :picdata="item"
            :picmargin="'-20px 10px 10px 10px'"
            :size="{ width:80, height:80 }"
            :piclist="mainPicList"
            @delPic="delMainPic"/>
        </el-form-item>
        <el-form-item label="主图缩略图" class="goods-form-item">
          <el-button type="primary" plain @click="openBriefPicPanel" size="small">选择图片</el-button>
          <div class="goods-form-item-text" style="width:calc(100% - 150px)">缩略图用于显示在首页，选择大图模式，建议上传600×350，最多上传一张，支持png、jpg、jpeg格式，大小不超过500KB</div>
        </el-form-item>
        <el-form-item class="goods-form-item" v-if="briefPicList.length>0">
          <l-pic v-for="(item,index) in briefPicList" :key="index"
            :picurl="item"
            :pickey="index"
            :picdata="item"
            :picmargin="'-20px 10px 10px 10px'"
            :size="{ width:80, height:80 }"
            :piclist="briefPicList"
            @delPic="delBriefMainPic"/>
        </el-form-item>
        <el-form-item label="主视频" class="goods-form-item">
          <div style="width:50%;display:inline-block">
            <el-upload :action="videoUrl" :show-file-list="false" :on-success="videoSuccess" :headers="{'Access-Token':token}" style="display:inline-block">
              <el-button type="primary" plain size="small">选择视频</el-button>
            </el-upload>
            <span style="padding:0 10px 0 20px">视频链接</span>
            <el-input v-model="goods.video_url" class="goods-form-item-input" placeholder="请输入" size="small" style="width:calc(100% - 280px)"></el-input>
            <el-button type="text" size="small" @click="goods.video_url = ''">删除</el-button>
          </div>
          <div class="goods-form-item-text">缩略图用于显示在首页，选择大图模式，建议上传600×350，最多上传一张，支持png、jpg、jpeg格式，大小不超过500KB</div>
        </el-form-item>
        <el-form-item class="goods-form-item" v-if="goods.video_url !== ''" style="height:150px">
          <video :src="goods.video_url" controls="controls" class="goods-form-item-video">
            您的浏览器不支持 video 标签。
          </video>
        </el-form-item>
      </div>

      <div class="goods-title">商品详情</div>
      <!-- 商品详情 -->
      <div style="padding: 10px 20px">
        <tinymce v-model="goods.detail_info" :height="300" width="600px" />
      </div>

      <div class="goods-title">价格规格库存</div>
      <!-- 价格规格库存 -->
      <div>
        <el-form-item label="规格设置" class="goods-form-item">
          <el-radio-group v-model="goods.stock_type" size="small" @change="goodsPropChange">
            <el-radio label="1" border>单规格</el-radio>
            <el-radio label="2" border>双规格</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 规格设置 -->
        <div v-for="(item, index) in property" :key="index">
          <el-form-item label="规格名称" class="goods-form-item">
            <el-input v-model="item.name" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
          </el-form-item>
          <el-form-item label="规格值" class="goods-form-item">
            <el-tag v-for="(value, count) in item.value" :key="count" closable :disable-transitions="false" style="margin-right:10px"
              @close="delProp(index, value)">{{ value }}</el-tag>
            <el-input
              class="input-new-tag"
              v-if="isPropInput&&propEditIndex === index"
              v-model="propValue"
              ref="savePropInput"
              size="small"
              @keyup.enter.native="setPropValue(index)"
              @blur="setPropValue(index)"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showPropInput(index)">+ 规格值</el-button>
          </el-form-item>
        </div>
        <!-- 规格明细表格 -->
        <el-divider content-position="left">规格明细</el-divider>
        <div class="prop-table">
          <el-row class="prop-table-header">
            <el-col :span="2">图片</el-col>
            <el-col :span="2">规格1</el-col>
            <el-col :span="2" v-if="goods.stock_type === '2'">规格2</el-col>
            <el-col :span="3">现价(元)</el-col>
            <el-col :span="3">重量(g)</el-col>
            <el-col :span="3">库存</el-col>
            <el-col :span="3">货号</el-col>
            <el-col :span="3">成本价</el-col>
          </el-row>
          <div style="padding: 10px 0" v-for="(item, index) in stock" :key="index+200">
            <div v-if="item.length === 0" style="padding: 15px 0">暂无规格值数据</div>
            <el-row class="prop-table-row" v-else>
              <el-col :span="2" class="prop-table-row-col">
                <div class="img-box-button" v-if="item.pic_url === ''" @click="disPropPicPanel = true; propImgIndex = index; propImgKey = index">
                  <i class="el-icon-plus" style="position:relative;bottom:4px;font-size:24px;font-weight:600;color:#999"></i>
                </div>
                <l-pic :picurl="item.pic_url" :size="{ width: 50, height: 50 }" picmargin="5px auto" v-else @delPic="item.pic_url = ''"/>
              </el-col>
              <el-col :span="2" class="prop-table-row-col">{{ item.property1_name }}</el-col>
              <el-col v-if="goods.stock_type === '2'" :span="2" class="prop-table-row-col">{{ item.property2_name }}</el-col>
              <el-col :span="3" class="prop-table-row-col">
                <el-input v-model="item.price" size="small" style="width:80%"></el-input>
              </el-col>
              <el-col :span="3" class="prop-table-row-col">
                <el-input v-model="item.weight" size="small" style="width:80%"></el-input>
              </el-col>
              <el-col :span="3" class="prop-table-row-col">
                <el-input v-model="item.number" size="small" style="width:80%"></el-input>
              </el-col>
              <el-col :span="3" class="prop-table-row-col">
                <el-input v-model="item.code" size="small" style="width:80%"></el-input>
              </el-col>
              <el-col :span="3" class="prop-table-row-col">
                <el-input v-model="item.cost_price" size="small" style="width:80%"></el-input>
              </el-col>
            </el-row>
          </div>
        </div>

        <el-form-item label="商品价格" class="goods-form-item" prop="price">
          <el-input v-model="goods.price" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
          <div class="goods-form-item-text" style="width:calc(80% - 100px)">商品销售的价格</div>
        </el-form-item>
        <el-form-item label="重量(g)" class="goods-form-item">
          <el-input v-model="goods.weight" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
        </el-form-item>
        <el-form-item label="划线价" class="goods-form-item">
          <el-input v-model="goods.line_price" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
        </el-form-item>
        <el-form-item label="库存" class="goods-form-item" prop="stocks">
          <el-input v-model="goods.stocks" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
          <div class="goods-form-item-text" style="width:calc(80% - 100px)">库存为0时，会放到[已售罄]的商品列表里，保存后，买家看到的商品可售库存同步更新</div>
        </el-form-item>
        <el-form-item class="goods-form-item">
          <el-switch v-model="cutPrice.isOpen"  active-color="#13ce66" active-value="1" inactive-value="0"></el-switch>
          <div class="goods-form-item-text" style="width:calc(80% - 100px)">库存为0时，是否自动下架，如不开启，库存为0，商品还会在首页正常显示，显示已售完</div>
        </el-form-item>
        <el-form-item label="虚拟销量" class="goods-form-item">
          <el-input v-model="goods.sales_number" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
          <div class="goods-form-item-text" style="width:calc(80% - 100px)">前端显示的虚拟销量，增加商品热度</div>
        </el-form-item>
        <el-form-item label="限量" class="goods-form-item">
          <el-switch v-model="goods.is_limit"  active-color="#13ce66" active-value="1" inactive-value="0"></el-switch>
          <el-input v-model="goods.limit_number" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
          <div class="goods-form-item-text" style="width:calc(80% - 100px)">限制单个用户最多购买数</div>
        </el-form-item>
      </div>

      <div class="goods-title">佣金设置</div>
      <!-- 佣金设置 -->
      <div>
        <el-form-item label="开启单独设置" class="goods-form-item">
          <el-switch v-model="goods.commission_is_open"  active-color="#13ce66" active-value="1" inactive-value="0"></el-switch>
          <div class="goods-form-item-text" style="width:calc(80% - 100px)">开启后，佣金设置将按照此处设置的比例计算，如不开启，将走总设置</div>
        </el-form-item>
        <!--<el-form-item label="推客佣金" class="goods-form-item">-->
          <!--<el-input v-model="goods.commission_selfleader_ratio" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>-->
          <!--<div class="goods-form-item-text" style="width:calc(80% - 100px)">%</div>-->
        <!--</el-form-item>-->
        <el-form-item label="团长佣金" class="goods-form-item">
          <el-input v-model="goods.commission_leader_ratio" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
          <div class="goods-form-item-text" style="width:calc(80% - 100px)">%</div>
        </el-form-item>
        <el-form-item label="分销佣金" class="goods-form-item">
          <el-input v-model="goods.distribution" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
          <div class="goods-form-item-text" style="width:calc(80% - 100px)">%</div>
        </el-form-item>
      </div>

      <div class="goods-title">其他信息</div>
      <!-- 其他信息 -->
      <div>
        <el-form-item label="上架时间" class="goods-form-item">
          <el-radio v-model="goods.start_type" label="0">立即上架</el-radio>
        </el-form-item>
        <el-form-item class="goods-form-item">
          <el-radio v-model="goods.start_type" label="1">自定义上架</el-radio>
          <el-date-picker v-if="goods.start_type === '1'" v-model="start_time" type="datetime" placeholder="选择上架时间" size="small"></el-date-picker>
        </el-form-item>
        <el-form-item class="goods-form-item">
          <el-radio v-model="goods.start_type" label="2">放入仓库，暂不售卖</el-radio>
        </el-form-item>
        <el-form-item label="下架时间" class="goods-form-item">
          <el-date-picker v-model="end_time" type="datetime" placeholder="选择下架时间" size="small"></el-date-picker>
        </el-form-item>
        <el-form-item label="提货时间" class="goods-form-item">
          <el-date-picker v-model="take_goods_time" type="datetime" placeholder="选择提货时间" size="small"></el-date-picker>
        </el-form-item>
        <el-form-item label="团长专属" class="goods-form-item">
          <el-switch v-model="goods.regimental_only"  active-color="#13ce66" active-value="1" inactive-value="0"></el-switch>
          <div class="goods-form-item-text" style="width:calc(80% - 100px)">开启后，该商品只有团长才能购买，未启用团购模式，无需开启</div>
        </el-form-item>
        <el-form-item label="排序" class="goods-form-item">
          <el-input v-model="goods.sort" class="goods-form-item-input" placeholder="请输入" size="small" style="width: 20%"></el-input>
        </el-form-item>
      </div>
    </el-form>

    <div style="text-align: center;margin-top:50px; position: fixed; left: 85%; top: 80%;">
      <el-button type="primary" style="padding:10px 30px;font-weight:600" @click="submit">提 交</el-button>
    </div>

    <!-- 相册面板 -->
    <Modal v-model="disPicPanel" width="1128" :footer-hide="true">
      <photo-album v-if="disPicPanel" :maxcount="maxPicCount" @selectPicData="getPicData"/>
    </Modal>

    <!-- 缩略图相册面板 -->
    <Modal v-model="disBriefPicPanel" width="1128" :footer-hide="true">
      <photo-album v-if="disBriefPicPanel" :maxcount="maxBriefPicCount" @selectPicData="getBriefPicData"/>
    </Modal>

    <!-- 规格图片选择面板 -->
    <Modal v-model="disPropPicPanel" width="1128" :footer-hide="true">
      <photo-album v-if="disPropPicPanel" :maxcount="1" @selectPicData="getPropPicData"/>
    </Modal>
  </div>
</template>

<script>
import { rules, cutPrice } from './goodsData'
import { getGoodsGroupList, getGoodsArea, postGoodsVideoUrl, postGoods, shopCircleGoods } from '@/api/addgoods'
import { putGoods } from '@/api/goods'
import PhotoAlbum from '@/components/PhotoAlbum'
import LPic from '@/components/lPic'
import Tinymce from '@/components/Tinymce'
import { getToken } from '@/utils/auth'

export default {
  name: 'Entity',
  components: {
    PhotoAlbum,
    LPic,
    Tinymce
  },
  props: {
    goods: {
      type: Object,
      required: true
    },
    isAdd: {
      type: Boolean,
      required: true
    },
    type: {
      type: Number
    }
  },
  data() {
    return {
      // goods: { key: this.$store.state.app.activeApp.saa_key, ...goods },
      rules: rules,

      id: 0,
      goodGroupList: [], //商品分组
      firstGroup: [],//一级分类
      firstGroupId: '',//选择的一级分类的ID
      secondGroupId: '',//选择的二级分类的ID

      goodsAreaList: [],//商品销售区域
      storehouseList: [],//仓库列表

      labels: [ '', '', '', '' ],

      disPicPanel: false, //打开相册面板
      maxPicCount: 5,//最多选择图片张数

      mainPicList: [],//商品主图列表

      disBriefPicPanel: false,//打开缩略图面板
      maxBriefPicCount: 1,//缩略图最多选择张数
      briefPicList: [],//缩略图

      videoUrl: postGoodsVideoUrl(),//上传视频的url
      token: getToken(),

      groupTypeList:[{ assemble_number: '', assemble_group_discount: '', discount: '' }],

      cutPrice: cutPrice, //砍价数据
      property: [], //规格
      //新增的时候保存的规格数据
      add_stock_pic: [],//规格图片
      add_stock_property1_name: [],//规格属性1
      add_stock_property2_name: [],//规格属性2
      add_stock_price: [],//规格价格
      add_stock_weight: [],//规格重量
      add_stock_number: [],//规格数量
      add_stock_code: [],//规格货号
      add_stock_cost_price: [],//规格成本价
      add_stock_assemble_price: [],//规格成本价
      add_property1: '',//规格1
      add_property2: '',//规格2
      stock: {},

      isPropInput: false,
      propEditIndex: 0,
      propValue: '',

      disPropPicPanel: false, //规格图片选择
      propImgIndex: 0,
      propImgKey: 0,

      other: '0',
      is_group: 0,//是否已加载分组
      start_time: '0',
      end_time: '0',
      take_goods_time: '0',
    }
  },
  watch: {
    goodGroupList(newValue,old) { //商品分组
      if(old.length === 0) {
        return;
      }
      if(newValue.length > 0) {
        this.firstGroupId = newValue[0].id;
        this.selectGoodsGroup();
      }
    },
    labels(newValue) { //增值服务
      this.goods.label = ''
      newValue.forEach((item,index) => {
        if(item.trim() !== ''){
          if(index < 3){
            this.goods.label += item + ','
          }else{
            this.goods.label += item
          }
        }
      });
    },
    groupTypeList(newValue) { //拼团类型
      if(this.goods.tuan_type === '1'){
        this.goods.assemble_number = newValue[0].assemble_number;
        this.goods.assemble_group_discount = newValue[0].assemble_group_discount;
      }
    },
    goods(value){
      this.goodsPropChange()
      if(value.pic_urls){
        this.mainPicList = value.pic_urls
      }
      if(value.hasOwnProperty('stock')){
        this.stock = value.stock
      }
      if(value.property1.length != 0){
        this.property = []
        this.$set(this.property, 0, {name: value.property1.split(':')[0], value: value.property1.split(':')[1].split(',')})
      }
      if(value.property2.length != 0){
        this.$set(this.property, 1, {name: value.property2.split(':')[0], value: value.property2.split(':')[1].split(',')})
      }
      //切换单多规格

      //只有当获取到分类id再判断如何展示商品分组
      if (value.category_id) {
        const group = this.goodGroupList.find(item => item.id === value.category_id);
        if(group) {
          this.firstGroupId = value.category_id;
          this.firstGroup = group.sub;
          const group_second = this.firstGroup.find(item_s => item_s.id === value.m_category_id);
          if(group_second) {
            this.secondGroupId = value.m_category_id;
          }
        }
      }

      this.start_time = value.format_start_time;
      this.end_time = value.format_end_time;
      this.take_goods_time = value.format_take_goods_time;
    }
  },
  mounted() {
    this.getGoodGroup();//获取商品分组
    this.getGoodsArea();//获取商品销售区域

    //设置labels
    this.labels = this.goods.label.split(',');
    for (let index = this.labels.length; index < 4; index++) {
      this.labels[index] = '';
    }

    //设置商品主图
    if (this.goods.type === '1'){
      this.mainPicList = [];
      this.goods.pic_urls.split(',').forEach(item => {
        if(item !== '' && item !== null && item !== undefined){
          this.mainPicList.push(item);
          this.maxPicCount --;
        }
      })
    }else {
      this.mainPicList = [...this.goods.pic_urls]
    }

    //切换单多规格
    this.goodsPropChange()

    //如果是编辑，则设置规格，id存在则为编辑
    if (this.goods.id) {
      this.stock = [];
      this.property = [];
      if (this.goods.have_stock_type === '1') {
        let p1 = this.goods.property1.split(':');
        this.property.push({name: p1[0], value: p1[1].split(',')});
        if (this.goods.stock_type === '2') {
          let p2 = this.goods.property2.split(':');
          this.property.push({name: p2[0], value: p2[1].split(',')});
        }
        this.stock = this.goods.stock;
      }
      //将时间改为format时间
      this.goods.start_time = this.goods.format_start_time;
      this.goods.end_time = this.goods.format_end_time;
      this.goods.take_goods_time = this.goods.format_take_goods_time;
    }
  },
  methods: {
    /**
     * 提交
     */
    submit() {
      this.goods.pic_urls = this.mainPicList
      this.$refs.goodsform.validate(valid => {
        if(valid) {
          //commission_selfleader_ratio commission_leader_ratio distribution\
          if(this.goods.detail_info == '' ){
            this.$message('请填写商品详情')
            return false
          }
          if (this.goods.commission_is_open === '0'){
            this.goods.commission_selfleader_ratio = '0';
            this.goods.commission_leader_ratio = '0';
            this.goods.distribution = '0';
          }
          this.goods.have_stock_type = 0;
          if (this.property.length > 0){
            let p1_key = this.property[0].name;
            let p1_value = this.property[0].value.join(',');
            if(this.property[0].value[0] != '' && this.property[0].value[0] != undefined){
              this.goods.property1 = p1_key + ':' + p1_value;
            }else{
              this.goods.property1 = ''
            }
            //判断是否有属性，类型为单属性时判断 property 0 中的value长度是否大于1，双属性则 property 0和1都要判断
            if (this.property[0].value.length > 0) {
              this.goods.have_stock_type = 1;
            }
            if (this.goods.stock_type === '2') {
              this.goods.property2 = this.property[1].name + ':' + this.property[1].value.join(',');
              if (this.property[1].value.length === 0) {
                this.goods.have_stock_type = 0;
              }
            }else{
              this.goods.property2 = ''
            }
          } else {
            this.goods.property1 = '';
          }

          //重组stock
          let goods_stock = this.stock;
          for (let i = 0; i < goods_stock.length; i++) {
            this.add_stock_pic.push(goods_stock[i].pic_url)
            this.add_stock_property1_name.push(goods_stock[i].property1_name)
            this.add_stock_property2_name.push(goods_stock[i].property2_name)
            this.add_stock_price.push(goods_stock[i].price)
            this.add_stock_weight.push(goods_stock[i].weight)
            this.add_stock_number.push(goods_stock[i].number)
            this.add_stock_code.push(goods_stock[i].code)
            this.add_stock_cost_price.push(goods_stock[i].cost_price)
            this.add_stock_assemble_price.push(goods_stock[i].assemble_price)
          }
          this.goods.stock = {
            pic_url: this.add_stock_pic,
            property1_name: this.add_stock_property1_name,
            property2_name: this.add_stock_property2_name,
            price: this.add_stock_price,
            weight: this.add_stock_weight,
            number: this.add_stock_number,
            code: this.add_stock_code,
            cost_price: this.add_stock_cost_price,
            assemble_price: this.add_stock_assemble_price,
          };

          this.goods.start_time = this.start_time;
          this.goods.end_time = this.end_time;
          this.goods.take_goods_time = this.take_goods_time;
          if (this.goods.start_time && this.goods.start_time !== '' && this.goods.start_time !== '0'){
            if (typeof this.goods.start_time === "string"){
              this.goods.start_time = new Date(Date.parse(this.goods.start_time.replace(/-/g,  "/")));
            }
            this.goods.start_time = this.formatDateTime(this.goods.start_time);
          }
          if (this.goods.end_time && this.goods.end_time !== '' && this.goods.end_time !== '0'){
            if (typeof this.goods.end_time === "string"){
              this.goods.end_time = new Date(Date.parse(this.goods.end_time.replace(/-/g,  "/")));
            }
            this.goods.end_time = this.formatDateTime(this.goods.end_time);
          }
          if (this.goods.take_goods_time && this.goods.take_goods_time !== '' && this.goods.take_goods_time !== '0'){
            if (typeof this.goods.take_goods_time === "string"){
              this.goods.take_goods_time = new Date(Date.parse(this.goods.take_goods_time.replace(/-/g,  "/")));
            }
            this.goods.take_goods_time = this.formatDateTime(this.goods.take_goods_time);
          }

          delete this.goods.group_info;
          delete this.goods.delete_time;
          delete this.goods.create_time;
          delete this.goods.update_time;
          delete this.goods.format_end_time;
          delete this.goods.format_take_goods_time;
          delete this.goods.format_start_time;
          delete this.goods.format_bargain_start_time;
          delete this.goods.format_bargain_end_time;
          if (this.goods.start_type !== '1') {
            this.goods.start_time = '0';
          }
          if (this.isAdd) {
            postGoods({...this.goods, pic_urls: this.goods.pic_urls.join(',')}).then(res => {
              if(res.status === 200) {
                this.goods.id = res.data;
                this.$message.success('添加成功！');
                //添加到好物圈
                shopCircleGoods({goods_id: this.goods.id, key: this.$store.state.app.activeApp.saa_key});
                this.$router.push('/goods/list');
              }else{
                this.$message.error(res.message);
              }
            })
          }else{
            // const params = upDateFormat(this.goods);
            this.goods.id = this.$route.query.id;
            putGoods({...this.goods, pic_urls: this.goods.pic_urls.join(',')}).then(res => {
              if(res.status === 200) {
                this.$message.success('修改成功！');
                //添加到好物圈
                shopCircleGoods({goods_id: this.goods.id, key: this.$store.state.app.activeApp.saa_key});
                this.$router.push('/goods/list');
              }else{
                this.$message.error(res.message);
              }
            })
          }
        }else {
          this.$message.error('请根据提示，完善商品信息！')
        }
      })
    },
    /**
     * 获取商品分组
     */
    getGoodGroup() {
      this.is_group = 0;
      getGoodsGroupList({ key: this.$store.state.app.activeApp.saa_key }).then(res => {
        if(res.status === 200){
          this.goodGroupList = res.data;
          if (this.goodGroupList.length > 0) {
            this.firstGroupId = this.goodGroupList[0].id;
            this.firstGroup = this.goodGroupList[0].sub;
            this.secondGroupId = this.goodGroupList[0].sub[0].id;
            this.goods.category_id = this.firstGroupId;
            this.goods.m_category_id = this.secondGroupId;
          }
          // if(this.goods.category_id!=="") {
          //   const group = this.goodGroupList.find(item => item.id === this.goods.category_id);
          //   if(group) {
          //     this.firstGroupId = this.goods.category_id;
          //   }else {
          //     this.goodGroupList.forEach(item => {
          //       if(item.sub) {
          //         const c = item.sub.find(item => item.id === this.goods.m_category_id);
          //         if(c) {
          //           this.firstGroupId = item.id;
          //           this.goods.category_id = item.id;
          //           this.goods.m_category_id = c.id;
          //           this.selectGoodsGroup();
          //         }
          //       }
          //     });
          //   }
          // }
        }else if(res.status === 204){
          this.goodGroupList = []
        }else{
          this.$message.error(res.message);
        }
      })
    },
    /**
     * 获取商品销售区域
     */
    getGoodsArea() {
      getGoodsArea({ key: this.$store.state.app.activeApp.saa_key, status: 1 }).then(res => {
        if(res.status === 200){
          this.goodsAreaList = res.data;
        }else if(res.status === 204){
          this.goodsAreaList = [];
        }else{
          this.$message.error(res.message);
        }
      })
    },
    /**
     * 选择商品分类
     */
    selectGoodsGroup() {
      const group = this.goodGroupList.find(item => item.id === this.firstGroupId);
      this.goods.category_id = this.firstGroupId;
      this.firstGroup = group === undefined ? [] : group.sub;
      if(this.firstGroup.length > 0){
        this.goods.m_category_id = this.firstGroup[0].id;
        this.secondGroupId = this.firstGroup[0].id;
      }else{
        this.goods.m_category_id = this.firstGroupId;
        this.secondGroupId = this.firstGroupId;
      }
    },
    /**
     * 选择商品二级分类
     */
    selectGoodsGroupSecond(e) {
      this.goods.m_category_id = this.secondGroupId = e;
    },
    /**
     * 打开主图选择面板
     */
    openMainPicPanel() {
      if(this.maxPicCount > 0){
        this.disPicPanel = true;
      }else{
        this.$message.warning(`最多可选择5张图片，已选择${5-this.maxPicCount}张,不可选择`);
      }
    },
    /**
     * 获取选择到的主图数据
     */
    getPicData(data) {
      this.disPicPanel = false;
      data.forEach(item => {
        if(this.maxPicCount > 0) {
          this.mainPicList.push(item.pic_url);
          this.maxPicCount --;
        }else{
          this.$message.warning(`最多可选择5张图片，已选择${5-this.maxPicCount}张`);
          return false
        }
      })
    },
    /**
     * 删除主图
     */
    delMainPic(data) {
      this.mainPicList.splice(this.mainPicList.findIndex(item => item===data),1);
      this.maxPicCount++;
    },
    /**
     * 打开缩略图面板
     */
    openBriefPicPanel() {
      if(this.maxBriefPicCount > 0) {
        this.disBriefPicPanel = true;
      }else{
        this.$message.warning('最多可选择1张图片，已选择1张,不可选择');
      }
    },
    /**
     * 获取选择到的缩略图数据
     */
    getBriefPicData(data) {
      this.disBriefPicPanel = false;
      data.forEach(item => {
        if(this.maxBriefPicCount > 0) {
          this.briefPicList.push(item.pic_url);
          this.maxBriefPicCount --;
        }else{
          this.$message.warning('最多可选择1张图片，已选择1张');
          return false
        }
      })
    },
    /**
     * 删除缩略图
     */
    delBriefMainPic(data) {
      this.briefPicList.splice(this.briefPicList.findIndex(item => item===data),1);
      this.maxBriefPicCount++;
    },
    /**
     * 上传视频成功
     */
    videoSuccess(response) {
      if(response.status === 200) {
        this.$message.success('上传成功！');
        this.goods.video_id = response.data.video_id;
        this.goods.video_pic_url = response.data.video_pic_url;
        this.goods.video_url = response.data.video_url;
      }else{
        this.$message.error(response.message);
      }
    },
    /**
     * 切换拼团类型
     */
    tuanTypeChange() {
      if(this.goods.tuan_type === '1') {
        if(this.groupTypeList.length >= 2){
          this.groupTypeList.splice(1,this.groupTypeList.length-1)
        }
      }
    },
    /**
     * 切换单多规格类型
     */
    goodsPropChange() {
      this.property = [];
      if(this.goods.stock_type === '1') {
        this.property.push({name: '', value: []});
      }else{
        this.property.push({name: '', value: []});
        if(this.property.length === 1) {
          this.property.push({name: '', value: []});
        }
      }
      this.stock = [];
    },
    /**
     * 显示添加属性值输入框
     */
    showPropInput(index) {
      this.isPropInput = true;
      this.propEditIndex = index;
      this.$nextTick(() => {
        this.$refs.savePropInput[0].$refs.input.focus();
      })
    },
    /**
     * 新增规格值
     */
    setPropValue(index) {
      let value = this.propValue;
      //如果是规格1，则循环规格2的值循环添加，如果是规格2，则循环规格1的值循环添加
      if(value) {
        if (this.goods.stock_type === '2'){
          if (index === 0) {
              //添加了规格1，循环规格2的所有属性值添加规格
              this.property[0].value.push(value);
              if (this.property[1] && this.property[1].value.length > 0) {
                let pro2 = this.property[1].value;
                for (let i = 0; i < pro2.length; i++) {
                    this.stock.push({ property1_name: value,property2_name: pro2[i],price: '',weight: '',cost_price: '',assemble_price: '',number: '', code: '', pic_url: ''});
                }
              }
          } else if (index === 1) {
              //添加了规格2，循环规格1的所有属性值添加规格
              this.property[1].value.push(value);
              if (this.property[0] && this.property[0].value.length > 0){
                let pro1 = this.property[0].value;
                for (let i = 0; i < pro1.length; i++) {
                    this.stock.push({ property2_name: value,property1_name: pro1[i],price: '',weight: '',cost_price: '',assemble_price: '',number: '', code: '', pic_url: ''});
                }
              }
          }
        } else {
          this.property[0].value.push(value);
          this.stock.push({ property1_name: value,property2_name: '',price: '',weight: '',cost_price: '',assemble_price: '',number: '', code: '', pic_url: ''});
        }
      }
      this.isPropInput = false;
      this.propValue = '';
    },
    /**
     * 删除规格值
     */
    delProp(index, value) {
      //删除属性值，先获取要删除的属性值的下标
      let io = this.property[index].value.indexOf(value);
      if (io !== -1){
        this.property[index].value.splice(io, 1)
      }
      //删除规格
      for (let i = this.stock.length - 1; i >= 0; i--){
        if ((index === 0 && this.stock[i].property1_name === value) || (index === 1 && this.stock[i].property2_name === value)) {
            this.stock.splice(i, 1)
        }
      }
    },
    /**
     * 获取选择的规格图片的值
     */
    getPropPicData(data) {
      this.disPropPicPanel = false;
      this.stock[this.propImgIndex].pic_url = data[0].pic_url;
    },
    formatDateTime (date) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h=h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second=date.getSeconds();
      second=second < 10 ? ('0' + second) : second;
      return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
    }
  },
}
</script>

<style lang="scss" scoped>
.goods-form{

}
.goods-title{
  height: 47px;
  width: 100%;
  line-height: 47px;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 2px;
  color: #8f8f8f;
  padding: 0 10px;
  background-color: #F4F8FB;
}
.goods-form-item{
  width: 100%;
  height: 50px;
  line-height: 50px;
  padding: 5px 0;
  box-sizing: border-box;
  &-input{
    width: 50%;
    height: 40px;
    line-height: 40px;
  }
  &-text{
    width: calc(50% - 100px);
    display: inline-block;
    height: 40px;
    line-height: 40px;
    padding: 0 0 0 20px;
    color: #c0c4cc;
    font-size: 14px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    vertical-align: middle;
  }
  &-button-text{
    width: calc(100% - 200px);
    display: inline-block;
    height: 40px;
    line-height: 40px;
    padding: 0 0 0 20px;
    color: #c0c4cc;
    font-size: 14px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    vertical-align: middle;
  }
  &-button{
    padding: 5px 10px;
    margin-left: 10px;
  }
  &-video{
    height: 150px;
    min-width: 200px;
    max-width: 100%;
  }
}

.group-type{
  width:calc(100% - 100px);
  display: inline-flex;
  &>div{
    flex: 1;
    padding-right: 10px;
  }
  &-title{
    // flex: 1;
    width: 80px;
    display: inline-block;
    padding: 0 5px 0 0;
    color: #909399;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    vertical-align: middle;
    // text-align: right;
  }
  &-input{
    width: calc(100% - 120px);
    height: 40px;
    line-height: 40px;
  }
  &-text{
    width: 100%;
    color: #c0c4cc;
    font-size: 14px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }
}
.cutprice-col{
  overflow:hidden;
  height: 40px;
}
.cutprice-title{
  width: 70px;
  display: inline-block;
  padding: 0 5px 0 0;
  color: #909399;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
  vertical-align: middle;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.prop-table{
  border: 1px dashed #eee;
  text-align: center;
  &-header{
    height: 30px;
    line-height: 30px;
    background-color: #F4F8FB;
  }
  &-row{
    height: 60px;
    line-height: 60px;
    &-col{
      height: 60px;
    }
  }
}
.img-box-button{
  height: 50px;
  width: 50px;
  border: 2px dashed #eee;
  border-radius: 4px;
  margin: 5px auto;
  cursor: pointer;
}
</style>
